package com.jwdf.uda.http.action;

import android.content.Context;
import android.os.Environment;

import com.jwdf.uda.app.AppContext;
import com.jwdf.uda.bean.UploadImageResponse;
import com.jwdf.uda.http.ApiFileUploadService;
import com.jwdf.uda.http.ApiServiceModule;
import com.jwdf.uda.utils.FileUtils;
import com.jwdf.uda.utils.LogUtils;
import com.jwdf.uda.utils.NETUtils;
import com.jwdf.uda.utils.ToastUtils;

import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

import okhttp3.MediaType;
import okhttp3.RequestBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import rx.Observable;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.functions.Func1;
import rx.schedulers.Schedulers;
import top.zibin.luban.Luban;

/**
 * 类说明：
 * 作者：huangqiuxin on 2016/5/23 11:01
 * 邮箱：648859026@qq.com
 */
public class UploadImageAction {
    private final static String TAG = UploadImageAction.class.getSimpleName();
    public final long UPLOAD_IMAGE_SIZE_LIMIT = 1024 * 1024;//1M

    protected Context context;
    protected ApiFileUploadService apiFileUploadService;
    private String imagePath;
    private boolean compress=true;
    private File uploadImageFile = null;

    public UploadImageAction(Context context, String imagePath) {
        this.context = context;
        apiFileUploadService = ApiServiceModule.getInstance().providerApiFileUploadService(context);
        this.imagePath = imagePath;
    }

    public UploadImageAction(Context context, String imagePath,boolean compress) {
        this(context,imagePath);
        this.compress=compress;
    }

    public interface IResCallback<T> {
        int RESULT_OK = 0;

        int RESULT_NOT_NET_ERROR = 1;

        int RESULT_UPIMAGE_ERROR = 2;

        int RESULT_FILE_NOTEXIT_ERROR = 3;

        int RESULT_OTHER_ERROR = 4;

        void onCallback(int resultCode, UploadImageResponse response);
    }

    /**
     * 发送请求数据
     *
     * @param iResCallback
     * @return
     */
    public Call request(final IResCallback<String> iResCallback) {
        if (!NETUtils.isNetworkConnected(context)) {
            //处理无网络情况
            if (iResCallback != null) {
                iResCallback.onCallback(IResCallback.RESULT_NOT_NET_ERROR, null);
            }
            return null;
        }
        File imageFile = null;
        try {
            imageFile = new File(new URI(imagePath));
        } catch (URISyntaxException e) {
            e.printStackTrace();
        }
        if (imageFile == null || !imageFile.exists()) {
            ToastUtils.show(context, "上传文件不存在！");
            iResCallback.onCallback(IResCallback.RESULT_FILE_NOTEXIT_ERROR, null);
            return null;
        }
        try {

            final Map<String, RequestBody> photos = new HashMap<>();

            //1M以上图片进行压缩处理
            if (imageFile.length() > UPLOAD_IMAGE_SIZE_LIMIT&&compress) {
                LogUtils.i(TAG, "uploadImage:" + imageFile.getAbsolutePath() + ",size:" + imageFile.length());
                String imageType = getImageType(imageFile.getAbsolutePath());
                final String filePath = imageFile.getAbsolutePath();
                try {
                    uploadImageFile = createTempImageFile(imageType);//将要保存图片的路径
                } catch (IOException e) {
                    e.printStackTrace();
                }
//                FileUtils.compressImageFile(filePath, uploadImageFile);
//                Observable<String> observable = Observable.create(new Observable.OnSubscribe<String>() {
//                    @Override
//                    public void call(Subscriber<? super String> subscriber) {
//                        FileUtils.compressImageFile(filePath, uploadImageFile);
//                        LogUtils.i(TAG, "uploadImageFile:" + uploadImageFile.getAbsolutePath() + ",size:" + uploadImageFile.length());
//                        subscriber.onNext(subscriber.toString());
//                        subscriber.onCompleted();
//                    }
//                }).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread());

                photos.put("upload_picture\"; filename=\"" + uploadImageFile.getName(), RequestBody.create(MediaType.parse("multipart/form-data"), uploadImageFile));
                final Call<UploadImageResponse> call = apiFileUploadService.uploadImages(photos);
//                UploadImageTask uploadImageTask=new UploadImageTask(call,iResCallback);
//                uploadImageTask.equals(imageFile);
//                enqueue(call, iResCallback);
//                observable.subscribe(new Subscriber<String>() {
//                    @Override
//                    public void onCompleted() {
//                        LogUtils.i(TAG, "onCompleted");
////                        enqueue(call, iResCallback);
//                    }
//
//                    @Override
//                    public void onError(Throwable e) {
//                        LogUtils.i(TAG, "onError:");
//                        e.printStackTrace();
//                    }
//
//                    @Override
//                    public void onNext(String s) {
//                        enqueue(call, iResCallback);
//                    }
//                });

//                Luban.get(AppContext.getInstance())
//                        .load(imageFile)                     //传人要压缩的图片
//                        .putGear(Luban.THIRD_GEAR)      //设定压缩档次，默认三挡
//                        .setFilename(uploadImageFile.getAbsolutePath())
//                        .setCompressListener(new OnCompressListener() { //设置回调
//
//                            @Override
//                            public void onStart() {
//                                // TODO 压缩开始前调用，可以在方法内启动 loading UI
//                            }
//                            @Override
//                            public void onSuccess(File file) {
//                                // TODO 压缩成功后调用，返回压缩后的图片文件
//                                enqueue(call, iResCallback);
//                            }
//
//                            @Override
//                            public void onError(Throwable e) {
//                                // TODO 当压缩过去出现问题时调用
//                                Log.i("--------","压缩失败");
//                            }
//                        }).launch();



                Luban.get(AppContext.getInstance())
                        .load(imageFile)
                        .putGear(Luban.THIRD_GEAR)
                        .setFilename(uploadImageFile.getAbsolutePath())
                        .asObservable()
                        .subscribeOn(Schedulers.io())
                        .observeOn(AndroidSchedulers.mainThread())
                        .doOnError(new Action1<Throwable>() {
                            @Override
                            public void call(Throwable throwable) {
                                throwable.printStackTrace();
                            }
                        })
                        .onErrorResumeNext(new Func1<Throwable, Observable<? extends File>>() {
                            @Override
                            public Observable<? extends File> call(Throwable throwable) {
                                return Observable.empty();
                            }
                        })
                        .subscribe(new Action1<File>() {
                            @Override
                            public void call(File file) {
                                // TODO 压缩成功后调用，返回压缩后的图片文件
                                enqueue(call, iResCallback);
                            }
                        });    //启动压缩


                return call;

            } else {
                photos.put("upload_picture\"; filename=\"" + imageFile.getName(), RequestBody.create(MediaType.parse("multipart/form-data"), imageFile));
                Call<UploadImageResponse> call = apiFileUploadService.uploadImages(photos);
                enqueue(call, iResCallback);
                return call;
            }
        } catch (Throwable e) {
            e.printStackTrace();
            if (iResCallback != null) {
                iResCallback.onCallback(IResCallback.RESULT_OTHER_ERROR, null);
            }
            delUploadImageFile();
        }
        return null;
    }

    private Call a(Call<UploadImageResponse> call, final IResCallback<String> iResCallback,File file, final Map<String, RequestBody> photos){
        photos.put("upload_picture\"; filename=\"" + file.getName(), RequestBody.create(MediaType.parse("multipart/form-data"), file));
        call = apiFileUploadService.uploadImages(photos);
        enqueue(call, iResCallback);
        return call;
    }

    private void enqueue(Call<UploadImageResponse> call, final IResCallback<String> iResCallback) {
        call.enqueue(new Callback<UploadImageResponse>() {
            @Override
            public void onResponse(Call<UploadImageResponse> call, Response<UploadImageResponse> response) {
                LogUtils.i(TAG, "onResponse");
                int responseCode = response.code();
                if (responseCode == 200) {
                    if (iResCallback != null) {
                        iResCallback.onCallback(IResCallback.RESULT_OK, response.body());
                    }
                } else {
                    try {
                        String msg = new String(response.errorBody().bytes());
                        LogUtils.i(TAG, "onResponse responseCode:" + responseCode + "," + msg);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    if (iResCallback != null) {
                        iResCallback.onCallback(IResCallback.RESULT_UPIMAGE_ERROR, null);
                    }
                }
                delUploadImageFile();
            }

            @Override
            public void onFailure(Call<UploadImageResponse> call, Throwable t) {
                LogUtils.i(TAG, "onFailure:");
                t.printStackTrace();
                if (iResCallback != null) {
                    iResCallback.onCallback(IResCallback.RESULT_UPIMAGE_ERROR, null);
                }
                delUploadImageFile();
            }
        });
    }

    private static File createTempImageFile(String imageType) throws IOException {
        // Create an image file name
        String imageFileName = "temp"+UUID.randomUUID();
        File storageDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
        if (!storageDir.exists()) {
            if (!storageDir.mkdir()) {
                throw new IOException();
            }
        }
        File image = new File(storageDir, imageFileName + imageType);
        return image;
    }

    private synchronized static String getImageType(String uri) {
        String[] array = uri.split("\\.");
        return "." + array[array.length - 1].toLowerCase();
    }

    private void delUploadImageFile() {
        if (uploadImageFile != null) {
            FileUtils.deleteTempFile(uploadImageFile.getAbsolutePath());
            uploadImageFile = null;
        }
    }




}
